package com.example.controller;

import com.example.entity.Comment;
import com.example.mapper.ArticleMapper;
import com.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ArticleMapper articleMapper;


    @GetMapping("/articles/{articleId}/comments")
    public List<Comment> getCommentsByArticleId(@PathVariable Integer articleId) {
        return commentService.getCommentsByArticleId(articleId);
    }

    @PostMapping("/articles/{articleId}/comments")
    public Comment addComment(@PathVariable Integer articleId, @RequestBody Comment comment) {
        // 调用服务层方法添加评论
        Comment addedComment = commentService.addComment(articleId, comment);

        // 增加文章的评论数
        int result = articleMapper.incrementCommentCount(articleId);
        if (result <= 0) {
            // 处理评论数增加失败的情况
            // 可以选择抛出异常或者返回错误信息
            throw new RuntimeException("文章评论数增加失败");
        }

        return addedComment;
    }
}

